//
//  NetGirlViewController.m
//  Auditory
//
//  Created by 寒竹子 on 15/5/4.
//  Copyright (c) 2015年 寒竹子. All rights reserved.
//

#define PicCollectionViewCellId @"PicCollectionViewCellId"
#define KBorder 8
#define PicWidth ([UIScreen mainScreen].bounds.size.width - KBorder * 3) / 2.0f
#define PageSize 20 // 每页的数据条数 20条
#define TypeTag_NetGirl  @"车模"

#import "PicModel.h"
#import "MyLayout.h"
#import "loadView.h"
#import "PicCollectionViewCell.h"
#import"MMMaterialDesignSpinner.h"
#import "PhotoViewController.h"
#import "RootNavigationController.h"
#import "UIViewController+MMSpinner.h"
#import "CheMoViewController.h"

@interface CheMoViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong) NSMutableArray * dataArray;
@property (nonatomic, strong) loadView * loader;
@property (nonatomic, assign) int page; // 页
@property (nonatomic, assign) BOOL isloadMore; // 是否正在加载更多

@end

@implementation CheMoViewController

- (instancetype)init
{
    if (self = [super init]) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    
    return self;
}

/**
 * @brief  下载数据
 *
 * @param
 * @return
 */
- (void)downloadData
{
    _page = 0;
    NSNumber * pageNumber = [NSNumber numberWithInt:_page];
    NSNumber * pageSizeNumber = [NSNumber numberWithInt:PageSize];
    
    NSDictionary * params = @{@"appid":@29560,
                              @"pn":pageNumber,
                              @"tag2":TypeTag_NetGirl,
                              @"rn":pageSizeNumber,
                              @"tag1":@"美女"};
    
    [self addMMSpinner];
    
    [Network getJSONWithBaseURL:PicBaseURL params:params returnCall:^(id JSON, NSError *error) {
        if (!error) {
            // 请求成功
            NSDictionary * dict = (NSDictionary *)JSON;
            NSArray * arr = dict[@"data"];
            for (int i = 0; i < arr.count; i++) {
                NSDictionary * dic = arr[i];
                PicModel * model = [[PicModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                
                // 计算每张图片的比例高度
                CGFloat image_W = [model.thumbnail_width floatValue];
                CGFloat image_H = [model.thumbnail_height floatValue];
                
                image_W = PicWidth;
                image_H = (PicWidth / image_W) * image_H;
                model.imageW = image_W;
                model.imageH = image_H;
                [_dataArray addObject:model];
            }
            
            [self removeMMSpinner];
            
            [self setupUI];
        }
    }];
}

- (UICollectionView *)collectionView
{
    if (nil != _collectionView) {
        // 创建布局
        _collectionView.collectionViewLayout = [[MyLayout alloc] initWithDataArray:[_dataArray copy]];
        
        return _collectionView;
    }
    
    // 创建布局
    MyLayout *layout = [[MyLayout alloc] initWithDataArray:[self.dataArray copy]];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = RGB(242, 242, 242, 1.0f);
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.showsVerticalScrollIndicator = NO;
    
    // 注册cell
    [_collectionView registerClass:[PicCollectionViewCell class] forCellWithReuseIdentifier:PicCollectionViewCellId];
    
    return _collectionView;
}

- (loadView *)loader
{
    if (nil == _loader) {
        _loader = [[loadView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 160) / 2.0f, self.view.frame.size.height - 25 - 30, 160, 25)];
    }
    
    return _loader;
}

- (void)setupUI
{
    self.view.backgroundColor = RGB(240, 240, 240, 1.0f);
    
    [self.view addSubview:self.collectionView];
}

/**
 * @brief  加载更多
 *
 * @param
 * @return
 */
- (void)loadMoreAction
{
    _isloadMore = YES;
    _page++;
    NSNumber * pageNumber = [NSNumber numberWithInt:_page];
    NSNumber * pageSizeNumber = [NSNumber numberWithInt:PageSize];
    
    NSDictionary * params = @{@"appid":@29560,
                              @"pn":pageNumber,
                              @"tag2":TypeTag_NetGirl,
                              @"rn":pageSizeNumber,
                              @"tag1":@"美女"};
    [self.loader display];
    [Network getJSONWithBaseURL:PicBaseURL params:params returnCall:^(id JSON, NSError *error) {
        if (!error) {
            // 请求成功
            NSDictionary * dict = (NSDictionary *)JSON;
            NSArray * arr = dict[@"data"];
            for (int i = 0; i < arr.count; i++) {
                NSDictionary * dic = arr[i];
                PicModel * model = [[PicModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                
                // 计算每张图片的比例高度
                CGFloat image_W = [model.thumbnail_width floatValue];
                CGFloat image_H = [model.thumbnail_height floatValue];
                
                image_W = PicWidth;
                image_H = (PicWidth / image_W) * image_H;
                model.imageW = image_W;
                model.imageH = image_H;
                [_dataArray addObject:model];
            }
            
            [self.collectionView reloadData];
            _isloadMore = NO;
            [self performSelector:@selector(hiddenLoaderAction) withObject:nil afterDelay:2.0f];
        }
    }];
}

- (void)hiddenLoaderAction
{
    [self.loader hidden];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self downloadData];
}

#pragma mark - UICollectionViewDelegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return _dataArray.count;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PicCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:PicCollectionViewCellId forIndexPath:indexPath];
    
    PicModel * model = self.dataArray[indexPath.item-1];
    cell.model = model;
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PicModel * model = _dataArray[indexPath.item - 1];
    PhotoViewController * photoVc = [[PhotoViewController alloc] initWithPicModel:model];
    
    [self.rootNav pushViewController:photoVc animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint currentOffSet = scrollView.contentOffset;
    CGRect frame = _collectionView.frame;
    
    if (currentOffSet.y == _collectionView.contentSize.height - frame.size.height || _collectionView.contentSize.height < frame.size.height) {
        if (!_isloadMore) {
            // 加载更多
            [self loadMoreAction];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end